import { think } from 'thinkjs';
import { IMessage, ISession } from '../../types';
import mongo from '../../../../../utils/mongo';
import { SchemaSession } from '../../types/model/Session';
import { IScene } from '../../types/base';

class ImSessionModel {
  /**
   * 更新或创建 Session
   */
  async createOrUpdateSession({
    sessionId,
    scene,
    account,
    to,
    msg,
    isTop,
    topCustom,
    custom,
    unread,
    unreadNum,
  }: {
    sessionId?: string;
    scene?: IScene;
    account: string;
    to?: string;
    msg?: IMessage;
    isTop?: boolean;
    topCustom?: object;
    custom?: object;
    /** true 则未读数+1 */
    unread?: boolean;
    /** 如果传入则重写未读数 */
    unreadNum?: number;
  }): Promise<{
    session: ISession;
  }> {
    // 传入SessionId创建会话的情况（基本没有以防万一）
    if (!sessionId && !(scene && to)) throw new Err('服务器错误#us');
    if (!scene || !to) {
      let sessionIdArr = sessionId.split('-');
      scene = sessionIdArr[0] as IScene;
      to = sessionIdArr[1];
    }
    // 初始化 Session
    let session: ISession = {
      scene,
      account,
      to,
    };
    const SessionModel = mongo.model('session', SchemaSession);
    // 查询已存在的会话记录
    let sessionInDb: ISession = await SessionModel.findOne(
      sessionId
        ? {
            account,
            sessionId,
          }
        : {
            scene,
            account,
            to,
          },
    );
    if (sessionInDb) {
      session = sessionInDb;
    }
    // 创建或更新字段
    if (msg) session.lastMsg = msg;
    if (isTop) session.isTop = isTop;
    if (topCustom) session.topCustom = topCustom;
    if (custom) session.topCustom = custom;
    if (unread) {
      session.unread = !!sessionInDb && sessionInDb.unread ? sessionInDb.unread + 1 : 1;
    }
    if (typeof unreadNum === 'number') {
      session.unread = unreadNum;
    }
    // 生成sessionId
    sessionId = scene + '-' + to;
    session.sessionId = sessionId;
    // 保存数据
    if (sessionInDb) {
      let updateSessionRes = await (session as any).save();
    } else {
      const newSession = new SessionModel(session);
      let { _id } = await newSession.save();
      session._id = _id;
    }
    return {
      session,
    };
  }

  /**
   * 删除会话
   */
  async deleteSession(account: string, scene: string, to: string) {
    const SessionModel = mongo.model('session', SchemaSession);
    const { deletedCount } = await SessionModel.remove({
      account,
      scene,
      to
    });
    if (deletedCount !== 1) {
      throw new Err('删除会话失败');
    }
  }

}

export default new ImSessionModel();
